#include "EditorMaterial.h"
#include "Editor.h"

namespace FinalRendering
{
	namespace Editor
	{
		using namespace Engine;

		EditorMaterial::EditorMaterial()
		{
			texture = new GxRendering::Texture();
		}

		GxRendering::Texture * EditorMaterial::GetTexture()
		{
			return texture.operator->();
		}

		void EditorMaterial::Load(const String &matPath, const String &fileName, bool upload)
		{
			MaterialFile file(matPath + fileName);
			MaterialFile::Uniform * uniform;
			uniform = file.FindUniform(L"editor_texture");
			if (uniform)
			{
				try
				{
					if (upload)
						texture->LoadFromFile(matPath+uniform->Value);
					else
						texture->LoadToMemory(matPath+uniform->Value);
				}
				catch(...)
				{
					texture->LoadErrorTexture();
				}
				if (upload)
					texture->ReleaseNativeMemory();
			}
			else
			{
				try
				{
					uniform = file.FindUniform(L"diffuse_map");
					if (!uniform)
					{
						texture->LoadErrorTexture();
					}
					else
					{
						if (upload)
							texture->LoadFromFile(matPath+uniform->Value);
						else
							texture->LoadToMemory(matPath+uniform->Value);
					}
				}
				catch(int)
				{
					texture->LoadErrorTexture();
				}
				if (upload)
					texture->ReleaseNativeMemory();
			}
		}

		void EditorMaterial::Bind()
		{
			if (texture)
			{
				glEnable(GL_TEXTURE_2D);
				texture->Bind();
			}
		}
	}
}